import os
import sys
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, BASE_DIR)
import socket
import time
import threading
from co.thread import thread_await
from co.thread import thread_run
from co.thread import thread_try
from co.thread import add_coroutine
from co.thread import tcp_connect
from co.thread import tcp_read
from co.thread import tcp_write
from co.thread import tcp_socket

#线程测试
@thread_try
def do_something(*args, **kwargs):
    print(f'do_something args {args}')
    seconds = 1
    if len(args):
        seconds = args[0]
    print (f'线程休眠{seconds}秒 pid {threading.current_thread().ident}')
    time.sleep(seconds)
    print(f'线程休眠{seconds}完毕 pid {threading.current_thread().ident}')

for i in range(1, 100):
    add_coroutine(thread_await(do_something, None, i%10))

# socket测试
@thread_try
def curl_get(url:str):
    sock = tcp_socket()
    if not tcp_connect(sock, (url, 80)):
        print(f'connect {url} failed')
        return
    get = f'GET http://{url} HTTP/1.0 \r\n Host: {url} \r\n\r\n'
    print(f'pid {threading.current_thread().ident} goto get {url}')
    yield from tcp_write(sock, get.encode('ascii'))

    response = yield from tcp_read(sock)
    data = b''.join(response)
    print(f'pid {threading.current_thread().ident} goto get {url} datalen {len(data)} \r\n')

urls = [
    'www.baidu.com111',
    'www.qq.com',
    'www.sina.com',
    'www.google.com',
]

for url in urls:
    add_coroutine(curl_get(url))

thread_run()